<template>
  <div class="writetaskcontainer">
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header">
        <span>试题录入</span>
      </div>
      <el-form
        :model="testForm"
        :rules="formRule"
        ref="RuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="学科:" prop="subjectID" label-width="120px">
          <el-select
            v-model="testForm.subjectID"
            @focus="subjectIDhandler"
            placeholder="请选择"
            style="width: 400px"
            @change="subjectIDchangehandler"
          >
            <!-- <el-option label="" value=""></el-option> -->
            <el-option
              v-for="(item, index) in subjectlist"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录:" prop="catalogID" label-width="120px">
          <el-select
            v-model="testForm.catalogID"
            placeholder="请选择"
            style="width: 400px"
            @focus="checkcataloghandler"
          >
            <el-option
              v-for="item in cataloglist"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业:" prop="enterpriseID" label-width="120px">
          <el-select
            v-model="testForm.enterpriseID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in getcompanyslist"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市 -->
        <el-form-item label="城市:" prop="province" label-width="120px">
          <el-select
            class="filter-item"
            style="width: 198px; margin-right: 4px"
            v-model="testForm.province"
            @change="handleProvince($event)"
          >
            <!-- filterable -->
            <!-- @keyup.enter="handleFilter" -->
            <el-option
              v-for="item in mapprovinces"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <el-select
            class="filter-item"
            style="width: 198px"
            v-model="testForm.city"
          >
            <!-- filterable -->
            <!-- @keyup.enter="handleFilter" -->
            <el-option
              v-for="item in mapcitys"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="方向:" prop="direction" label-width="120px">
          <el-select
            v-model="testForm.direction"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="(item, index) in directionlist"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型:" label-width="120px" prop="questionType">
          <el-radio-group v-model="testForm.questionType">
            <el-radio
              style="display: inline-block; padding-right: 0"
              v-for="item in questionType"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <!-- <el-form-item label="123" size="normal">
  <el-radio-group >
    <el-radio :label="3">备选项</el-radio>
    <el-radio :label="6">备选项</el-radio>
    <el-radio :label="9">备选项</el-radio>
  </el-radio-group>
</el-form-item> -->

        <el-form-item label="难度:" label-width="120px" prop="difficulty">
          <el-radio-group v-model="testForm.difficulty">
            <el-radio
              style="display: inline-block; padding-right: 0"
              v-for="item in difficulty"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- 富文本1 -->
        <el-form-item label="题干:" label-width="120px" prop="question">
          <quill-editor
            v-model.trim="testForm.question"
            ref="oneQuillEditor"
            :options="editorOption"
            @blur="questionEditorBlur()"
          >
            <!-- @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
            @change="onEditorChange($event)" -->
          </quill-editor>
        </el-form-item>

        <el-form-item
          v-show="testForm.questionType !== 3"
          label="选项:"
          label-width="120px"
        >
          <!-- 选项组件 -->
          <el-radio-group
            v-show="testForm.questionType === 1"
            v-model="radiocode"
          >
            <optionArea
              :radiocode="radiocode"
              ref="radioOption"
              v-for="item in num"
              :key="item"
              :codeindex="alp[item - 1]"
            ></optionArea>
          </el-radio-group>
          <!-- 多选 -->
          <el-checkbox-group
            v-show="testForm.questionType === 2"
            v-model="codelist"
          >
            <optionArea
              :codelist="codelist"
              ref="CheckboxOption"
              :btntype="false"
              v-for="item in num"
              :key="item"
              :codeindex="alp[item - 1]"
            ></optionArea>
          </el-checkbox-group>

          <el-row :gutter="20" style="margin: 0">
            <el-button
              type="danger"
              size="mini"
              @click="addoptionhandler"
              :disabled="showaddoptionbtn"
              v-text="'+增加选项与答案'"
            ></el-button>
          </el-row>
        </el-form-item>
        <el-form-item label="解析视频:" label-width="120px" prop="videoURL">
          <el-input
            style="width: 400px"
            v-model="testForm.videoURL"
            placeholder="请输入视频URL地址"
          ></el-input>
        </el-form-item>
        <!-- 富文本2 -->
        <el-form-item label="答案解析:" label-width="120px" prop="answer">
          <quill-editor
            v-model.trim="testForm.answer"
            :options="editorOption"
            @blur="answerEditorBlur()"
            ref="otherQuillEditor"
          >
            <!-- @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
            @change="onEditorChange($event)" -->
          </quill-editor>
        </el-form-item>

        <el-form-item label="题目备注:" label-width="120px" prop="remarks">
          <el-input
            :rows="4"
            type="textarea"
            class="remarkstextarea"
            v-model.trim="testForm.remarks"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="试题标签:" label-width="120px" prop="tags">
          <el-select
            style="width: 400px"
            v-model="testForm.tags"
            filterable
            multiple
            default-first-option
            placeholder="请选择"
            @focus="checktaghandler"
          >
            <el-option
              v-for="(item, index) in taglist"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item size="normal">
          <el-button
            v-if="$route.query.id"
            type="success"
            size="medium"
            @click="submithandler"
            >确认修改</el-button
          >
          <el-button v-else type="primary" size="medium" @click="submithandler"
            >确认添加</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { difficulty, questionType, direction } from '@/api/hmmm/constants.js'
import optionArea from '@/module-hmmm/components/optionArea'
import { quillEditor } from 'vue-quill-editor' // 调用编辑器
// 接口
import { simple, catalog } from '@/api/hmmm/subjects'
import { list } from '@/api/hmmm/companys'
import { simpleById } from '@/api/hmmm/tags'
import { add, detail, update } from '@/api/hmmm/questions'
// 富文本文件
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { provinces, citys } from '@/api/hmmm/citys.js'
export default {
  name: 'MiammianQuestionsNew',
  components: {
    quillEditor,
    optionArea
  },
  created () {
    this.difficulty = difficulty
    this.questionType = questionType
    this.directionlist = direction
    this.getCityData()
    this.getcompanys()
    this.subjectIDhandler()
    this.getdetailinfo()
  },
  data () {
    const checkinnercity = (rule, value, callback) => {
      this.testForm.subjectID &&
        !this.testForm.city &&
        callback(new Error('请选择市区域'))
      callback()
    }
    // const checkquestionhandler = (rule, value, callback) => {
    //   console.log(123)
    //   if (!this.testForm.question) {
    //     // this.$refs.RuleForm.validateField('question')
    //     callback(new Error('请填写题干'))
    //   } else {
    //     this.$refs.testForm.clearValidate('question')
    //   }
    // }

    return {
      testForm: {
        remarks: '',
        tags: [],
        answer: '',
        videoURL: '',
        question: '',
        difficulty: 1,
        questionType: 1,
        options: [],
        direction: '',
        province: '',
        city: '',
        enterpriseID: '',
        catalogID: '',
        subjectID: ''
      },
      sign: '',
      alp: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'k', 'L'],
      subjectlist: [], // 学科列表
      cataloglist: [], // 目录列表
      getcompanyslist: [], // 公司列表
      mapprovinces: [],
      mapcitys: [],
      difficulty: [],
      questionType: [],
      directionlist: [],
      // 单选时为单个字符串字母
      radiocode: '',
      // 多选时为数组
      codelist: [],
      num: 4,
      taglist: [],
      // 所有子组件数据
      antheroptions: [],
      formRule: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [{ validator: checkinnercity, trigger: 'change' }],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        question: [{ required: true, message: '请填写题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请填写答案解析', trigger: 'blur' }]
      },
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote'], // 引用，代码块
            ['code-block', 'image', 'video'] // 上传图片、上传视频
          ]
        }
      }
    }
  },
  computed: {
    showaddoptionbtn () {
      return this.testForm.questionType === 1 || this.num >= 10
    }
  },
  methods: {
    async getdetailinfo () {
      this.sign = this.$route.query || ''
      if (this.sign.id) {
        const { data } = await detail(this.sign)
        const { questionType, difficulty, options, tags } = data
        this.testForm = {
          ...data,
          questionType: Number(questionType),
          difficulty: Number(difficulty),
          tags: JSON.parse(tags instanceof Array) ? JSON.parse(tags) : []
        }
        if (questionType === '1') {
          // this.$refs.radioOption.forEach(async (item, index) => {
          //   item.optionitem = { ...options[index] }
          // })
          const refradio = this.$refs.radioOption
          if (options.length >= 4) this.num = options.length
          for (
            let i = 0;
            i <= (options.length && options.length <= 4 ? 3 : options.length);
            i++
          ) {
            refradio[i].optionitem = { ...options[i] }
            if (i >= options.length) {
              // 这里在初始化的时候没有保留多余的字段,但要注意的是code必须动态初始化,不然对应组件能监听但不能比较传过来的codeindex,所以isRight无法为true
              refradio[i].optionitem = {
                code: this.alp[i],
                title: '',
                img: '',
                isRight: false
              }
            }
          }
          const newArray = options.map((item) => {
            const { code, title, img, isRight } = item
            return { code, title: title.trim(), img, isRight }
          })
          this.radiocode = newArray.length
            ? newArray.filter((item) => item.isRight)[0]?.code
            : ''
        } else if (questionType === '2') {
          this.$refs.CheckboxOption.forEach(async (item, index) => {
            item.optionitem = { ...options[index] }
          })
          const newArray = options.map((item) => {
            const { code, title, img, isRight } = item
            return { code, title: title.trim(), img, isRight }
          })
          this.codelist = newArray.length
            ? newArray.filter((item) => item.isRight).map((item) => item?.code)
            : []
        } else {
          this.testForm.options = []
        }
      }
    },
    questionEditorBlur () {
      if (!this.testForm.question) {
        this.$refs.RuleForm.validateField('question')
      } else {
        this.$refs.RuleForm.clearValidate('question')
      }
    },
    answerEditorBlur () {
      if (!this.testForm.answer) {
        this.$refs.RuleForm.validateField('answer')
      } else {
        this.$refs.RuleForm.clearValidate('answer')
      }
    },
    checktaghandler () {
      if (!this.testForm.subjectID) {
        this.taglist = [{ value: '', label: '请先选择学科' }]
      }
    },
    checkcataloghandler () {
      if (!this.testForm.subjectID) {
        this.cataloglist = [{ value: '', label: '请先选择学科' }]
      }
    },
    // 添加选项的函数
    addoptionhandler () {
      this.num++
      if (this.num === 10) {
        this.$message.warning('最多有10个选项')
      }
    },
    async getcompanys () {
      const {
        data: { items }
      } = await list()
      this.getcompanyslist = items
    },
    async subjectIDhandler () {
      // 获取最新的simple表
      const { data } = await simple()
      this.subjectlist = data
      // 转成字符串格式
    },
    // 当学科change时根据id获取目录
    subjectIDchangehandler (value) {
      if (value && this.testForm.subjectID) {
        this.testForm.catalogID = ''
        this.testForm.tags = []
        this.taglist = []
        this.cataloglist = []
        setTimeout(async () => {
          const { data } = await catalog(this.testForm.subjectID)
          this.cataloglist = data
          const { data: taglist } = await simpleById(this.testForm.subjectID)
          this.taglist = taglist
        }, 0)
      }
    },
    async submithandler () {
      const result = await this.$refs.RuleForm.validate()
      if (!result) this.$message.error('请补全必填项')
      try {
        if (this.testForm.questionType === 1) {
          const radioOption = this.$refs.radioOption
          radioOption.forEach(async (item) => {
            const { code, title, img, isRight } = item.optionitem
            console.log(title)
            const obj = { code, title: title?.trim(), img, isRight }
            this.antheroptions.push(obj)
          })
          // 如果默认的单选且选项区没有任何内容放行,多选不进行此操作
          if (
            !this.antheroptions.every(
              (item) => !item.isRight && !item.title && !item.img
            )
          ) {
            let sign = ''
            for (let i = this.antheroptions.length - 1; i >= 0; i--) {
              if (
                this.antheroptions[i].title ||
                this.antheroptions[i].img ||
                this.antheroptions[i].isRight
              ) {
                sign = i
                break
              }
            }
            this.antheroptions.splice(sign + 1)
            if (this.antheroptions.every((item) => !item.isRight)) {
              this.antheroptions = []
              this.$message.error('请指定正确的选项')
              console.log('不符合')
              return false
            }
            if (this.antheroptions.some((item) => !item.title && !item.img)) {
              this.antheroptions = []
              this.$message.error('请补全空白的选项')
              console.log('不符合')
              return false
            }
            if (this.antheroptions.length <= 1) {
              this.antheroptions = []
              this.$message.error('请至少保留两个选项')
              console.log('不符合')
              return false
            }
          }

          this.testForm.options = this.antheroptions
          this.testForm.tags = JSON.stringify(this.testForm.tags)
          this.testForm.difficulty = String(this.testForm.difficulty)
          this.testForm.questionType = String(this.testForm.questionType)
          if (this.sign.id) {
            // this.testForm.id = this.sign.id
            await update(this.testForm)
            console.log(this.testForm)
            this.$message.success('修改成功')
            this.antheroptions = []
            // 清空子组件的optionitem对象的值
            radioOption.forEach((item) => {
              item.clearcomponent()
            })
          } else {
            await add(this.testForm)
            this.$message.success('添加成功')
            this.antheroptions = []
            // 清空子组件的optionitem对象的值
            radioOption.forEach((item) => {
              item.clearcomponent()
            })
          }
        } else if (this.testForm.questionType === 2) {
          const CheckboxOption = this.$refs.CheckboxOption
          CheckboxOption.forEach(async (item) => {
            const { code, title, img, isRight } = item.optionitem
            const obj = { code, title: title.trim(), img, isRight }
            this.antheroptions.push(obj)
          })
          let sign = ''
          for (let i = this.antheroptions.length - 1; i >= 0; i--) {
            if (
              this.antheroptions[i].title ||
              this.antheroptions[i].img ||
              this.antheroptions[i].isRight
            ) {
              sign = i
              break
            }
          }
          this.antheroptions.splice(sign + 1)
          if (this.antheroptions.every((item) => !item.isRight)) {
            this.antheroptions = []
            this.$message.error('请指定正确的选项')
            console.log('不符合')
            return false
          }
          if (this.antheroptions.some((item) => !item.title && !item.img)) {
            this.antheroptions = []
            this.$message.error('请补全空白的选项')
            console.log('不符合')
            return false
          }
          if (this.antheroptions.filter((item) => item.isRight).length < 2) {
            this.antheroptions = []
            this.$message.error('多选题型至少两个正确答案')
            console.log('不符合')
            return false
          }

          this.testForm.options = this.antheroptions
          this.testForm.tags = JSON.stringify(this.testForm.tags)
          this.testForm.difficulty = String(this.testForm.difficulty)
          this.testForm.questionType = String(this.testForm.questionType)

          if (this.sign.id) {
            // this.testForm.id = this.sign.id
            await update(this.testForm)
            this.$message.success('修改成功')
            this.antheroptions = []
            // 清空子组件的optionitem对象的值
            CheckboxOption.forEach((item) => {
              item.clearcomponent()
            })
          } else {
            await add(this.testForm)
            this.$message.success('添加成功')
            this.antheroptions = []
            CheckboxOption.forEach((item) => {
              item.clearcomponent()
            })
          }
        } else {
          this.antheroptions = []
          this.testForm.options = []
          this.testForm.tags = JSON.stringify(this.testForm.tags)
          this.testForm.difficulty = String(this.testForm.difficulty)
          this.testForm.questionType = String(this.testForm.questionType)
          await add(this.testForm)
          this.$message.success('添加成功')
        }
      } catch (err) {
        this.$message.error('添加失败!')
        return Promise.reject(new Error(err.message))
      }
      this.testForm = {
        remarks: '',
        tags: [],
        answer: '',
        videoURL: '',
        question: '',
        difficulty: 1,
        questionType: 1,
        options: [],
        direction: '',
        province: '',
        city: '',
        enterpriseID: '',
        catalogID: '',
        subjectID: ''
      }
      this.num = 4
      this.$refs.RuleForm.resetFields()
      this.$refs.RuleForm.clearValidate('province')
      console.log('符合')
      this.$router.push('/questions/list')
    },
    getCityData () {
      this.mapprovinces = provinces()
    },
    // 选省获取到市
    handleProvince (e) {
      this.testForm.city = ''
      this.mapcitys = citys(e)
    }
  }
}
</script>
<style lang="scss" scoped>
.writetaskcontainer {
  padding: 20px;
  .el-textarea {
    width: 400px;
  }
  ::v-deep .ql-editor {
    height: 200px;
  }
  ::v-deep label {
    padding-right: 20px;
  }
  ::v-deep .el-form-item__content {
    margin-left: 120px !important;
  }
}
</style>
